package org.aaron.wbclient.oauth;

import org.aaron.wbclient.TencentWeiBoClientActivity;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class RetrieveAccessTokenTask extends AsyncTask<Uri, Uri, Void> {

	private OAuthConsumer oAuthConsumer;
	private OAuthProvider oAuthProvider;
	private Context context;
	private SharedPreferences preference;

	public RetrieveAccessTokenTask() {
	}

	public RetrieveAccessTokenTask(OAuthConsumer oAuthConsumer, OAuthProvider oAuthProvider, Context context, SharedPreferences preference) {
		super();
		this.oAuthConsumer = oAuthConsumer;
		this.oAuthProvider = oAuthProvider;
		this.context = context;
		this.preference = preference;
	}

	@Override
	protected Void doInBackground(Uri... params) {
		Uri uri = params[0];
		final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
		try {
			oAuthProvider.retrieveAccessToken(oAuthConsumer, oauth_verifier);
			final Editor editor = preference.edit();
			editor.putString(OAuth.OAUTH_TOKEN, oAuthConsumer.getToken());
			editor.putString(OAuth.OAUTH_TOKEN_SECRET, oAuthConsumer.getTokenSecret());
			editor.commit();
			oAuthConsumer.setTokenWithSecret(preference.getString(OAuth.OAUTH_TOKEN, ""), preference.getString(OAuth.OAUTH_TOKEN_SECRET, ""));
			Log.d("ACCESS TOKEN RETRIEVE", "ACCESS TOKEN RETRIEVE");
			context.startActivity(new Intent(context, TencentWeiBoClientActivity.class));
		} catch (OAuthMessageSignerException e) {
			e.printStackTrace();
		} catch (OAuthNotAuthorizedException e) {
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			e.printStackTrace();
		}
		return null;
	}
}
